package com.lin.springbootinit.job;

import cn.hutool.core.util.StrUtil;
import com.lin.springbootinit.manager.CosManager;
import com.lin.springbootinit.mapper.GeneratorMapper;
import com.lin.springbootinit.model.entity.Generator;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestBody;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 每天定时清理任务
 */
@Component
@Slf4j
public class ClearCosJobHandler {


    @Resource
    private CosManager cosManager;

    @Resource
    private GeneratorMapper generatorMapper;

    @XxlJob("clearCosJobHandler")
    public void clearCosJobHandler() throws Exception {
        log.info("ClearCosJobHandler 开始清理 COS 文件");
        // 1: 用户上传的模板制作文件
        cosManager.deleteDir("/generator_make_template/");

        // 2：已经在数据库中删除的产物包文件
        List<Generator> generatorList = generatorMapper.listDeleteCosDir();
        List<String> keyList = generatorList.stream().map(Generator::getDistPath)
                .filter(StrUtil::isNotBlank)
                // 过滤 / 前缀
                .map(distPath ->distPath.substring(1))
                .collect(Collectors.toList());
        cosManager.deleteObjects(keyList);
        log.info("ClearCosJobHandler 结束清理 COS 文件");
    }
}
